//
//  KINGUserAccount.swift
//  肉荣微博
//
//  Created by king on 15/7/30.
//  Copyright © 2015年 king. All rights reserved.
//

import UIKit

class KINGUserAccount: NSObject, NSCoding{
    
    ///用于保存用户信息，提高效率
    static var userAccount:KINGUserAccount?
    ///计算属性，每次调用都会重新执行
    class var isLogin:Bool {
        return loadUserInfo() == nil
    }
    ///access_token用户证书
    var access_token: String?
    /// 证书过期时间
    var expiresDate: NSDate?
    var expires_in: NSTimeInterval = 0 {
        didSet {
            //在set方法中对过期时间进行转换
            expiresDate = NSDate(timeIntervalSinceNow: expires_in)
        }
    }
    /// 用户id
    var uid: String?
    /// 用户名称
    var name: String?
    /// 用户头像url
    var avatar_large: String?
    
    init(dict : [String : AnyObject]) {
        super.init()
        setValuesForKeysWithDictionary(dict)
        KINGUserAccount.userAccount = self
    }
    
    func loadUserIcon(finished:()->()){
        KINGNetworkTools.sharedTools.loadUserInfo(uid!) { (result, error) -> () in
            if error != nil {
                print(error)
                return
            }
            print(result)
            self.name = result!["name"] as? String
            self.avatar_large = result!["avatar_large"] as? String
            print(self)
            self.saveUserInfo()
            finished()
        }
    }

    //定义为static的时候，属性就是类的属性了，不能直接对其尽心访问，需要使用类进行访问
    static private let accountPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last?.stringByAppendingPathComponent("account.plist")
    /// 归档方法
    func saveUserInfo () {
        NSKeyedArchiver.archiveRootObject(self, toFile: KINGUserAccount.accountPath!)
        KINGUserAccount.userAccount = self
        print("保存数据\(KINGUserAccount.accountPath!)")
    }
    
    /// 解档函数优化，嵌套层次减少
    class func loadUserInfo() -> KINGUserAccount? {
        if userAccount == nil {
            userAccount = NSKeyedUnarchiver.unarchiveObjectWithFile(accountPath!) as? KINGUserAccount
        }
        //如果删掉程序，第一次没有存档userAccount为空  就会导致程序崩溃
        if let isUserAccount = userAccount {
            if isUserAccount.expiresDate?.compare(NSDate()) == NSComparisonResult.OrderedAscending {
                userAccount = nil
            }
        }
        return userAccount
    }
    
    // 之所以不直接使用loadUserInfo是因为还要做一次硬盘操作，只要我们保证，调用这个方法的时候，userAccount有值即可
    class func currentUserAccount() -> KINGUserAccount{
        return KINGUserAccount.userAccount!
    }
    //MARK: - 归档&解档
    //归档 保存数据
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeDouble(expires_in, forKey: "expires_in")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(expiresDate, forKey: "expiresDate")
        aCoder.encodeObject(name, forKey: "name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
    }
    //解档  读取数据
    required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        expires_in = aDecoder.decodeDoubleForKey("expires_in")
        uid = aDecoder.decodeObjectForKey("uid") as? String
        expiresDate = aDecoder.decodeObjectForKey("expiresDate") as? NSDate
        name = aDecoder.decodeObjectForKey("name") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
    }
    
    //MARK: - 重写description
    //疑问 这里到底是一个属性还是一个方法，为啥不用遵守协议
    override var description: String {
        let dict = ["access_token", "expires_in", "uid", "expiresDate", "name", "avatar_large"]
        return "\(dictionaryWithValuesForKeys(dict))"
    }
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {    }
}
